# -*- coding: utf-8 -*-
# 关键字驱动
import os
import shutil
import subprocess
import sys
from time import sleep

from common.utils.common_functions import exit_program
from common.utils.licensee import Licensee


class Keywords:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            # 创建新的实例
            instance = super().__new__(cls)
            cls._instance = instance
        return cls._instance

    def __init__(self):
        # 判断实例是否已经初始化
        if not hasattr(self, 'authorization_time'):
            licensee = Licensee()
            self.is_provide_demo = licensee.is_provide_demo
            self.adb = "adb"
            if not shutil.which("adb"):
                if os.path.exists("lib/platform-tools/adb.exe"):
                    print("未找到 adb 环境，使用本地：lib/platform-tools/adb.exe")
                    self.adb = "lib/platform-tools/adb.exe"
                else:
                    exit_program("未找到 adb")

    def connect_device(self, device_identifier):
        adb_devices = subprocess.run([self.adb, "devices"], capture_output=True, text=True)
        output = adb_devices.stdout
        lines = output.splitlines()
        found = False
        offline = False
        for line in lines:
            if device_identifier in line:
                found = True
                if "offline" in line:
                    offline = True
                    break
        if found and offline:
            if self.is_provide_demo:
                print(self.adb, "disconnect", device_identifier)
                print(self.adb, "connect", device_identifier)
            else:
                subprocess.run([self.adb, "disconnect", device_identifier])
                subprocess.run([self.adb, "connect", device_identifier])
        elif not found:
            if self.is_provide_demo:
                print(self.adb, "connect", device_identifier)
            else:
                subprocess.run([self.adb, "connect", device_identifier])

    # 判断设备是否连接
    def is_connect_device(self, device_identifier):
        try:
            result = subprocess.check_output([self.adb, "devices"])
            result = result.decode('utf-8')
            # 检查输出中是否包含指定的 device 且不包含 offline
            lines = result.splitlines()
            for line in lines:
                parts = line.split()
                if len(parts) >= 2 and parts[0] == device_identifier:
                    if parts[1] == "device":
                        print(f"{device_identifier} 设备已连接")
                        return True
                    elif parts[1] == "offline":
                        print(f"{device_identifier} is offline")
                        return False
            print(f"{device_identifier} 设备未连接，请确认连接状态")
            return False
        except subprocess.CalledProcessError as e:
            print(f"{device_identifier} 设备未连接，请确认连接状态")
            print(f"Error: {e}")
            return False

    # 触摸屏幕指定坐标
    def app_tap(self, loc, device_identifier):
        """x, y"""
        if self.is_provide_demo:
            print("{} -s {} shell input tap {} {}".format(self.adb, device_identifier, loc[0], loc[1]))
        else:
            os.popen("{} -s {} shell input tap {} {}".format(self.adb, device_identifier, loc[0], loc[1]))

    # 滑动
    def app_swipe(self, loc, device_identifier):
        """t, x1, y1, x2, y2"""
        if self.is_provide_demo:
            print("{} -s {} shell input swipe {} {} {} {} {}"
                  .format(self.adb, device_identifier, loc[0], loc[1], loc[2], loc[3], loc[4]))
        else:
            os.popen("{} -s {} shell input swipe {} {} {} {} {}"
                     .format(self.adb, device_identifier, loc[0], loc[1], loc[2], loc[3], loc[4]))

    # 输入数据
    def app_text(self, loc, device_identifier):
        """text"""
        if self.is_provide_demo:
            print("{} -s {} shell input text {}".format(self.adb, device_identifier, loc[0]))
        else:
            os.popen("{} -s {} shell input text {}".format(self.adb, device_identifier, loc[0]))

    # 键盘输入
    def app_keyevent(self, loc, device_identifier):
        """parameter"""
        if self.is_provide_demo:
            print("{} -s {} shell input keyevent {}".format(self.adb, device_identifier, loc[0]))
        else:
            os.popen("{} -s {} shell input keyevent {}".format(self.adb, device_identifier, loc[0]))

    # 强制等待
    def app_sleep(self, loc, device_identifier):
        """s"""
        sleep(int(loc[0]))





